package com.shigen.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shigen.demo.dao.UserMapper;
import com.shigen.demo.entity.Result;
import com.shigen.demo.entity.User;
import com.shigen.demo.valid.AddGroup;
import com.shigen.demo.valid.UpdateGroup;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * (SysUser)表控制层
 *
 * @author makejava
 * @since 2022-03-05 17:06:46
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserMapper userMapper;

    @PostMapping(value = "add")
    public Result<String> add(@RequestBody @Validated(value = AddGroup.class) User user) {
        int insert = userMapper.insert(user);
        return insert > 0 ? Result.ok(null) : Result.err(null);
    }

    @PostMapping(value = "update")
    public Result<String> update(@RequestBody @Validated(value = UpdateGroup.class) User user) {
        int update = userMapper.updateById(user);
        return update > 0 ? Result.ok(null) : Result.err(null);
    }

    @GetMapping(value = "get")
    public Result<List<User>> get(@RequestParam(value = "id", required = false) Integer id,
                                  @RequestParam(value = "name", required = false) String name
    ) {
        LambdaQueryWrapper<User> queryChainWrapper = new LambdaQueryWrapper<>();
        queryChainWrapper.eq(id != null, User::getId, id);
        queryChainWrapper.eq(name != null, User::getUsername, name);
        List<User> records = userMapper.selectPage(new Page<User>(0, 10), queryChainWrapper).getRecords();
        return Result.ok(records);
    }
}
